package com.hongxun.design.activitys;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.acceptance.mode.ProjectItem;
import com.hongxun.design.acceptance.mode.problemExist;
import com.hongxun.design.acceptance.mode.problemExistPhoto;
import com.hongxun.design.adapters.SelectProjectAdapter;
import com.hongxun.design.bean.Exploration;
import com.hongxun.design.bean.ProjectItemBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.IntentToActivity;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ShardPreferencesTool;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.dialogstyle.MyDialog;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.ui.ui_listview.refreshlist.SwipeRefreshListView;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.fileutil.FileUtil;
import com.hongxun.design.utils.fileutil.GetFileUtil;
import com.hongxun.design.utils.fileutil.SetFileUtil;
import com.hongxun.design.utils.fileutil.ZipUtil;
import com.hongxun.design.utils.projectdatautil.DataFactory;
import com.hongxun.design.utils.wifiutil.WifiHostUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zerdoor_pc on 2016/7/20.
 */
public class SelectProjectActivity extends BaseActivity implements HeadSecond, SwipeRefreshLayout.OnRefreshListener {
    SwipeRefreshListView listview;
    List<ProjectItemBean> data;
    SelectProjectAdapter adapter;
    String json;
    EditText serch_words;
    int type = 0;
    private RelativeLayout relativeLayout;
    private String uppath = "";
    private ProjectItemBean itemBean;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    getData();
                    handler.sendEmptyMessage(2);
                    break;
                case 2:
                    if (adapter == null) {
                        adapter = new SelectProjectAdapter(mActivity, data);
                        adapter.setType(type, handler);
                        listview.setAdapter(adapter);
                    } else {
                        adapter.notifyDataSetChanged();
                    }
                    listview.setRefreshing(false);
                    break;
                case Constant.NETLOAD://网络上传
                    onRefresh();
                    break;
                case Constant.FACELOAD://面对面快传
                    Bundle bundle = new Bundle();
                    bundle.putInt(MString.TYPE, Constant.send);
                    if (msg.arg1 == 0) {
                        bundle.putString(MString.stage_id, data.get(msg.arg2).getUUID());
                    } else {
                        bundle.putString(MString.stage_id, msg.arg1 + "");
                    }
                    bundle.putString(MString.CODE, (String) msg.obj);
                    String path = MString.Project_ + MString.getValueId(data.get(msg.arg2).getStage_id(), data.get(msg.arg2).getUUID());
                    if (DataFactory.check_cache(mActivity, path)) {
                        IntentToActivity.intent(mActivity, FaceSendAndReceiveActivity.class, bundle);
                    } else {
                        ToastShow.showShort(mActivity, "此项目没有缓存！");
                    }
                    break;
                case Constant.CODELOAD://发送二维码
                    String s = (String) msg.obj;
                    MyDialog.openCodeImage(mActivity, s);
                    break;
                case 99://同步数据
                    itemBean = (ProjectItemBean) msg.obj;
                    showWaitDialog(-1, "同步中...");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            List<problemExist> exPro = DataFactory.getExPro(MyApp.context);
                            List<problemExistPhoto> photos = DataFactory.getExProPh(MyApp.context);
                            if (exPro != null && !exPro.isEmpty()) {
                                zipYsLocalData(exPro, photos);
                            } else {
                                handler.sendEmptyMessageDelayed(97, 500);
                            }
                        }
                    }).start();
                    break;
                case 97:
                    hideWaitIngDialog();
                    DataFactory.ProjectloadClick(mActivity, itemBean, handler);
                    break;
                case 98:
                    MyApp.HTTP.uploadProYHAndPic(handler, 96, new File(uppath), SetFileUtil.CheckStageId_type());
                    break;
                case 96:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            upDataLocal();
                        }
                    }).start();
                    break;
            }
        }
    };

    //next_msg:97
    //把本地数据状态：已同步
    private void upDataLocal() {
        ShardPreferencesTool.save(MyApp.context, itemBean.getProject_id(), MString.xmDTB, 1);
        List<problemExist> exPro = DataFactory.getExPro(MyApp.context);
        List<problemExistPhoto> photos = DataFactory.getExProPh(MyApp.context);
        if (!exPro.isEmpty()) {
            List<problemExist> exProUp = new ArrayList<>();
            exProUp.addAll(exPro);
            List<problemExistPhoto> photosUp = new ArrayList<>();
            photosUp.addAll(photos);
            for (problemExist exist : exProUp) {
                if (exist.getProjectId().equals(itemBean.getStage_id())) {
                    if (exist.getStates().equals("删除")) {
                        exPro.remove(exist);
                    } else {
                        int indexOf = exPro.indexOf(exist);
                        exist.setStates(MString.xmYTB);
                        exPro.set(indexOf, exist);
                    }
                    for (problemExistPhoto photo : photosUp) {
                        if (exist.getGuid().equals(photo.getProblemExistGuid())) {
                            if (photo.getStates().equals("删除")) {
                                MyApp.File.delect(photo.getPhoneUrls());
                                photos.remove(photo);
                            } else {
                                int indexOf = photos.indexOf(photo);
                                photo.setStates(MString.xmYTB);
                                photos.set(indexOf, photo);
                            }
                        }
                    }
                }
            }
            //更新本地验收记录数据
            DataFactory.saveExPro(MyApp.context, FastJsonUtil.beanToJson(exPro));
            DataFactory.saveExProPh(MyApp.context, FastJsonUtil.beanToJson(photos));
        }
        handler.sendEmptyMessageDelayed(97, 500);
    }

    //next_msg:98
    private void zipYsLocalData(List<problemExist> exPro, List<problemExistPhoto> photos) {
        List<problemExist> exProUp = new ArrayList<>();
        List<problemExistPhoto> photosUp = new ArrayList<>();
        for (problemExist exist : exPro) {
            if (exist.getProjectId().equals(itemBean.getStage_id())) {
                if (!exist.getStates().equals(MString.xmYTB)) {
                    exProUp.add(exist);
                }
                for (problemExistPhoto photo : photos) {
                    if (exist.getGuid().equals(photo.getProblemExistGuid())) {
                        if (!photo.getStates().equals(MString.xmYTB)){
                            photosUp.add(photo);
                        }
                    }
                }
            }
        }
        //ys上传项目验收记录
        ProjectItem item = new ProjectItem();
        item.setProblemExistList(exProUp);
        item.setProblemExistPhotoList(photosUp);

        String toJson = FastJsonUtil.beanToJson(item);
        String idType = SetFileUtil.CheckStageId_type();

        String currPath = MyApp.File.getCachaPhotoPath_YH();
        String name = MString.projectStageYhInfo_ + idType + ".tio";
        String filepath = currPath + "/" + name;
        if (new File(filepath).exists()) {
            FileUtil.deleteFile(filepath);
        }
        String dir = idType + "/" + MString.projectYhJL + "/Photo_" + idType;
        MyApp.File.SaveFileDataAll(dir, name, toJson);
        //zip照片及数据
        try {
            uppath = ZipUtil.zipFolder(currPath);
        } catch (Exception e) {
            e.printStackTrace();
            hideWaitIngDialog();
        }
        handler.sendEmptyMessageDelayed(98, 3000);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_selectproject);
        findBar();
        findView();
    }


    @Override
    public void findBar() {
        Bundle bundle = getIntent().getExtras();
        type = bundle.getInt(MString.TYPE);
        flag = false;
        HeadSecondControlPanel headsecond_layout = (HeadSecondControlPanel) findViewById(R.id.selectproject_layout);
        relativeLayout = (RelativeLayout) findViewById(R.id.selectproject_rlayout);
        if (type == Constant.NETLOAD) {
            relativeLayout.setVisibility(View.GONE);
            headsecond_layout.initHeadPanel(DataUtil.getsecondbean("", View.GONE, R.color.bar_right, ListenerSet.back, "数据上传", R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
        } else {
            relativeLayout.setVisibility(View.VISIBLE);
            headsecond_layout.initHeadPanel(DataUtil.getsecondbean("", View.GONE, R.color.bar_right, ListenerSet.back, "选择项目", R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));
        }
    }

    boolean flag = false;

    @Override
    protected void onResume() {
        if (flag) {
            WifiHostUtil.getInstance(mActivity).closeWifi();
        }
        flag = true;
        super.onResume();
    }


    @Override
    protected void findView() {
        super.findView();
        TextView serch_button = (TextView) findViewById(R.id.serch_button);
        serch_words = (EditText) findViewById(R.id.serch_words);
        SetTypeface.set(serch_button, IconSourse.SEARCH);
        serch_button.append(" 搜索");
        listview = (SwipeRefreshListView) findViewById(R.id.selectproject_listview);
        listview.setOnRefreshListener(this);
        listview.setDivider(6);
        getData();
        adapter = new SelectProjectAdapter(this, data);
        adapter.setType(type, handler);
        listview.setAdapter(adapter);
        if (type != Constant.NETLOAD)
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    if (type == Constant.NETLOAD) {
                        DataFactory.ProjectloadClick((Activity) view.getContext(), data.get(i), handler);
                    } else {
                        if (type == Constant.FACELOAD && check(data.get(i))) {
                            ToastShow.showShort(MyApp.activity, "该项目为在线项目，无法进行文件传输！");
                            return;
                        }
                        ProjectItemBean curr = data.get(i);
                        ProjectItemBean info = FastJsonUtil.JsonToGetProject(GetFileUtil.getProjectInfo(SetFileUtil.CheckStageId_type(curr)));
                        curr.setBeanWithNo(info);
                        MyDialog.dialogForSelectPro((Activity) view.getContext(), handler, type, i, data.get(i), JSON.toJSONString(curr));
                    }
                }
            });
    }

    private boolean check(ProjectItemBean bean) {
        if (bean.getStage_id() == null || bean.getStage_id().length() == 0 || bean.getStage_id().equals("0")) {
            //离线文件
            return false;
        } else {
            //在线文件
            List<Exploration> list_11 = GetFileUtil.getExplorationList(bean, "11");
            List<Exploration> list_12 = GetFileUtil.getExplorationList(bean, "12");
            if (list_11 == null) list_11 = new ArrayList<>();
            if (list_12 == null) list_12 = new ArrayList<>();
            List<Exploration> data = new ArrayList<>();
            if (list_11.size() > 0) data.addAll(list_11);
            if (list_12.size() > 0) data.addAll(list_12);
            if (data.size() == 0) return false;
            for (Exploration e : data) {
                if (e.getExploration_id() != null && e.getExploration_id().length() > 0 && !e.getExploration_id().equals(MString.code_zero)) {
                    return true;
                }
            }
            return false;

        }
    }

    @Override
    public void onRefresh() {
        String words = serch_words.getText().toString();
        if (words.length() == 0) {
            handler.sendEmptyMessage(1);
        } else {
            listview.setRefreshing(false);
        }
    }

    private void getData() {
        if (data == null) data = new ArrayList<>();
        data.clear();
        data.addAll(GetFileUtil.getProjectStageListFile());
    }

    /**
     * 搜索*
     */
    public void Search(View v) {
        String words = serch_words.getText().toString();
        if (words.length() == 0) {
            handler.sendEmptyMessage(1);
        } else {
            List<ProjectItemBean> searchData = new ArrayList<>();
            for (ProjectItemBean p : data) {
                if (p.getProject_name().contains(words)) {
                    searchData.add(p);
                }
            }
            data.clear();
            data.addAll(searchData);
            handler.sendEmptyMessage(2);
        }
    }

}
